<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="title" :visible.sync="isShow" @close="close">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="getEmployeeList">
          <el-option v-for="item in employeesList" :key="item.id" :label="item.username" :value="item.username" />

        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="add">确定</el-button>
        <el-button size="small" @click="isShow = false">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartmentsInfo, editDepartments } from '@/api/departments'
import { getEmployeeSimpleList } from '@/api/employees'
export default {
  name: 'AddDept',
  props: {
    nodeData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    // 检测部门名称是否重复
    const checkNameRepeat = async(rules, value, callback) => {
      // 思路：找到当前点击部门的子部门数据；将输入的值和这些子部门数据的name进行匹配，找到就代表重复
      const { data } = await getDepartments() // 所有部门的数据
      let isRepeat = false
      if (this.formData.id) {
        // 修改：找到兄弟们（pid相同），除我之外还有同名
        isRepeat = data.depts.filter(item => item.pid === this.nodeData.id && item.id !== this.formData.id).some(item => item.name === value)
      } else {
        isRepeat = data.depts.filter(item => item.pid === this.nodeData.id).some(item => item.name === value)
      }
      return isRepeat ? callback(new Error(`同级已经存在${value}这个部门名称`)) : callback()
    }
    // 检测部门码是否重复
    const checkCodeRepeat = async(rules, value, callback) => {
      const { data } = await getDepartments() // 所有部门的数据
      let isRepeat = false
      if (this.formData.id) {
        // 修改：除了我自己之外
        isRepeat = data.depts.filter(item => item.pid === this.nodeData.id && item.id !== this.formData.id).some(item => item.name === value)
      } else {
        // 添加
        isRepeat = data.depts.filter(item => item.id !== this.formData.id).some(item => item.code === value && value)
      }
      return isRepeat ? callback(new Error(`同级已经存在${value}这个部门编码`)) : callback()
    }
    return {
      isShow: false,
      // 表单
      formData: {},
      // 员工列表
      employeesList: [],
      // 定义校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' }

        ],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-50个字符' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改部门' : '添加部门'
    }
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeSimpleList()
      this.employeesList = res.data
    },
    // 获取表单回显的数据
    async getInfoData(id) {
      const res = await getDepartmentsInfo(id)
      console.log(res)
      this.formData = res.data
    },
    // 发送请求
    async add() {
      if (this.formData.id) {
        // 修改
        await editDepartments(this.formData)
        this.$message.success('修改成功')
      } else {
        // 添加
        await addDepartments({ ...this.formData, pid: this.nodeData.id })
        this.$message.success('添加成功')
      }
      this.isShow = false
      this.$emit('update')
    },
    // 关闭的时候清空表单
    close() {
      this.formData = {}
    }
  }
}
</script>

<style>

</style>
